package com.winning.devops.batch.reader.ch04.config;

import com.winning.devops.batch.reader.ch04.domain.Customer;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.xstream.XStreamMarshaller;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chensj
 * @date 2020-03-01 21:02
 */
@Configuration
public class XmlFileItemReaderDemoConfig {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;
    @Autowired
    @Qualifier("xmlFileItemReaderDemoItemWriter")
    private ItemWriter<? super Customer> xmlFileItemReaderDemoItemWriter;

    @Bean
    public Job xmlFileItemReaderDemoJob() {
        return jobBuilderFactory.get("xmlFileItemReaderDemoJob")
                .start(xmlFileItemReaderDemoStep())
                .build();
    }

    @Bean
    public Step xmlFileItemReaderDemoStep() {
        return stepBuilderFactory
                .get("xmlFileItemReaderDemoStep")
                .<Customer, Customer>chunk(2)
                .reader(xmlFileItemReaderDemoItemReader())
                .writer(xmlFileItemReaderDemoItemWriter)
                .build();
    }

    @Bean
    @StepScope
    public StaxEventItemReader<Customer> xmlFileItemReaderDemoItemReader() {
        StaxEventItemReader<Customer> reader = new StaxEventItemReader<>();
        // 设置读取文件位置
        reader.setResource(new ClassPathResource("test.xml"));
        // 设置读取规则
        // 设置处理的根标签
        reader.setFragmentRootElementName("customer");
        // 解析规则 把xml转换为对象
        XStreamMarshaller unMarshaller = new XStreamMarshaller();
        // 指定标签转换到什么类型
        Map<String, Class> map = new HashMap<>();
        map.put("customer", Customer.class);
        map.put("id", Integer.class);
        map.put("firstName", String.class);
        map.put("lastName", String.class);
        map.put("birthday", String.class);
        unMarshaller.setAliases(map);

        reader.setUnmarshaller(unMarshaller);
        return reader;
    }
}
